package com.wanggsx.library.util;

import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.MyLocationStyle;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import static android.content.Context.SENSOR_SERVICE;

public class UtilsMapManager {

    /**
     * 全局的map容器，存储所有地图工具
     */
    private static Map<Activity, UtilsMapManager> mapUtilsMap = new HashMap<>();

    /**
     * 单例模式
     */
    private UtilsMapManager() {
    }

    /**
     * 根据Activity对象获取地图
     */
    public static UtilsMapManager getInstance(Activity act) {
        if (mapUtilsMap.containsKey(act)) {
            return mapUtilsMap.get(act);
        } else {
            UtilsMapManager utilsMap = new UtilsMapManager();
            utilsMap.mActivity = new WeakReference<>(act);
            mapUtilsMap.put(act, utilsMap);
            return utilsMap;
        }
    }

    /**
     * 地图相关api
     */
    private WeakReference<MapView> mMapView;
    private WeakReference<Activity> mActivity;
    private AMap aMap;
    private SensorManager sm;
    private Sensor mSensor;
    private SensorEventListener mSensorListener;
    public AMapLocationClient mLocationClient;//定位发起端
    private LocationSource.OnLocationChangedListener mLocationChangeListener;//定位源变化监听器
    private AMapLocationListener mLocationListener;//定位监听

    public void init(MapView mapView, AMapLocationListener mLocationListener, SensorEventListener sensorListener) {
        this.mMapView = new WeakReference<>(mapView);
        this.mLocationListener = mLocationListener;
        this.mSensorListener = sensorListener;
        init1(mLocationListener, sensorListener);
    }

    private void init1(AMapLocationListener mLocationListener, SensorEventListener sensorListener) {
        MapView map = mMapView.get();
        if (map != null) {
            aMap = map.getMap();
            //设置显示定位按钮 并且可以点击
            UiSettings settings = aMap.getUiSettings();
            //初始化定位蓝点样式类
            MyLocationStyle myLocationStyle = new MyLocationStyle();
            //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
            myLocationStyle.interval(2000);
            //设置定位蓝点的Style
            SensorManager sm = (SensorManager) mActivity.get().getSystemService(SENSOR_SERVICE);
            mSensor = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
            aMap.setMyLocationStyle(myLocationStyle);
            myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
            myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
            aMap.setLocationSource(new LocationSource() {
                @Override
                public void activate(OnLocationChangedListener onLocationChangedListener) {
                    mLocationChangeListener = onLocationChangedListener;
                    mLocationClient.startLocation();
                }

                @Override
                public void deactivate() {
                    mLocationChangeListener = null;
                }
            });//设置了定位的监听,这里要实现LocationSource接口
            // 是否显示定位按钮
            settings.setMyLocationButtonEnabled(true);
            // 添加方向感应
            mSensorListener = sensorListener;
            if (mSensorListener == null) {
//                mSensorListener = new SensorEventListener() {
//                       @Override
//                       public void onSensorChanged(SensorEvent event) {
//                           if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
//                               float degree = event.values[0];
//                               float bearing = aMap.getCameraPosition().bearing;
//                               if (degree + bearing > 360)
//                                   aMap.setMyLocationRotateAngle(degree + bearing - 360);// 设置小蓝点旋转角度
//                               else
//                                   aMap.setMyLocationRotateAngle(degree + bearing);
//                           }
//                       }
//
//                       @Override
//                       public void onAccuracyChanged(Sensor sensor, int accuracy) {
//
//                       }
//                   };
            } else {
                sm.registerListener(mSensorListener, mSensor, SensorManager.SENSOR_DELAY_UI);
            }
            mLocationClient = new AMapLocationClient(mActivity.get().getApplicationContext());
            //初始化定位参数
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否只定位一次,默认为false
            mLocationOption.setOnceLocation(false);
            //设置是否强制刷新WIFI，默认为强制刷新
            mLocationOption.setWifiActiveScan(true);
            //设置是否允许模拟位置,默认为false，不允许模拟位置
            mLocationOption.setMockEnable(false);
            //设置定位间隔,单位毫秒,默认为2000ms
            mLocationOption.setInterval(2000);
            //给定位客户端对象设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            //添加定位监听
            if (mLocationListener != null) {
                mLocationClient.setLocationListener(mLocationListener);
            }
            aMap.setMyLocationEnabled(true);//显示定位层并且可以触发定位,默认是flase
        }
    }

    /**
     * 开启定位
     */
    public void startMyLocation() {
        if (mLocationClient == null) return;
        mLocationClient.startLocation();
    }

    /**
     * 停止定位
     */
    public void stopMyLocation() {
        if (mLocationClient == null) return;
        mLocationClient.stopLocation();
    }

    public void destory() {
        if (sm != null) {
            sm.unregisterListener(mSensorListener);
            sm = null;
        }
        mLocationClient.onDestroy();
    }

    public AMap getAMap() {
        return this.aMap;
    }

}
